<?php


namespace app\logic\index\user;


use app\common\lib\Common;
use app\common\lib\TencentCos;
use app\common\lib\TextToImage;
use app\exception\IndexException;
use app\logic\BaseLogic;
use app\model\user\UserPromotionOverseaRollingImgModel;
use support\Log;

class UserPromotionOverseaRollingImgLogic extends BaseLogic
{

    public function __construct()
    {
        parent::__construct();
    }

    public static function getInstance()
    {
        return new self();
    }

    /**
     * 文字生成图片
     * @throws IndexException
     */
    public function textToImg($userSn, $planId, $content)
    {
        $width = 1080;
        $maxHeight = 1920;
        $fontSize = 57;
        $lineHeight = 1.5261;//经过调试得出这个数字适合设计给出的图
        $fontFile = base_path() . "/resources/font/HONORSans-Medium.ttf";
        $outPutPath = runtime_path() . "/img/{$userSn}/{$planId}/";
        // 实例化对象，不指定字体，使用系统默认字体
        $image = new TextToImage($width, $maxHeight, $fontSize, $lineHeight, $fontFile, $outPutPath);
        $image->setPadding(6, 256, 0, 256); // 设置上下左右边距
        $image->setShadow(true, [0, 0, 0, 50], 0, 4); // 设置阴影
        $image->setFontColor(255, 255, 255, 5); // 设置字体颜色为白色，透明度100
        $images = $image->setText($content);

        $imgUrl = [];
        foreach ($images as $img) {
            $name = substr(md5(round(microtime(true) * 10000) . Common::rand_string(8)), -20) . '.png';
            $res = TencentCos::getInstance()->uploadLocalFile($img, "user/rolling/image", $name);
            $imgUrl[] = 'https://' . $res['Location'];
            @unlink($img);
        }

        $data = [
            'user_sn' => $userSn,
            'user_planid' => $planId,
            'images' => json_encode($imgUrl)
        ];

        $res = UserPromotionOverseaRollingImgModel::getInstance()->insert($data);
        if (!$res) {
            throw new IndexException('滚动字幕图片入库失败');
        }
        return true;
    }
}